package l2ft.gameserver.taskmanager;

import java.util.concurrent.Future;

import l2ft.commons.threading.RunnableImpl;
import l2ft.commons.util.Rnd;
import l2ft.gameserver.Config;
import l2ft.gameserver.ThreadPoolManager;
import l2ft.gameserver.model.Player;
import l2ft.gameserver.model.instances.NpcInstance;

public class RepeatingTaskManager
{
	private static final RepeatingTaskManager _instance = new RepeatingTaskManager();

	public static final RepeatingTaskManager getInstance()
	{
		return _instance;
	}

	public Future<?> addPCCafePointsTask(final Player player)
	{
		long delay = Config.ALT_PCBANG_POINTS_DELAY * 60000L;

		return ThreadPoolManager.getInstance().scheduleEffectAtFixedRate(new RunnableImpl(){

			@Override
			public void runImpl() throws Exception
			{
				if(player.isInOfflineMode() || player.getLevel() < Config.ALT_PCBANG_POINTS_MIN_LVL)
					return;

				player.addPcBangPoints(Config.ALT_PCBANG_POINTS_BONUS, Config.ALT_PCBANG_POINTS_BONUS_DOUBLE_CHANCE > 0 && Rnd.chance(Config.ALT_PCBANG_POINTS_BONUS_DOUBLE_CHANCE));
			}

		}, delay, delay);
	}

	public Future<?> addVitalityRegenTask(final Player player)
	{
		long delay = 60000L;

		return ThreadPoolManager.getInstance().scheduleEffectAtFixedRate(new RunnableImpl(){

			@Override
			public void runImpl() throws Exception
			{
				if(player.isInOfflineMode() || !player.isInPeaceZone())
					return;

				player.setVitality(player.getVitality() + 1);
			}

		}, delay, delay);
	}

	public Future<?> addNpcAnimationTask(final NpcInstance npc)
	{
		return ThreadPoolManager.getInstance().scheduleEffectAtFixedRate(new RunnableImpl(){

			@Override
			public void runImpl() throws Exception
			{
				if(npc.isVisible() && !npc.isActionsDisabled() && !npc.isMoving && !npc.isInCombat())
					npc.onRandomAnimation();
			}

		}, 1000L, Rnd.get(Config.MIN_NPC_ANIMATION, Config.MAX_NPC_ANIMATION) * 1000L);
	}
	
	public Future<?> addAutoSaveTask(final Player player)
	{
		long delay = Rnd.get(180, 360) * 1000L;

		return ThreadPoolManager.getInstance().scheduleAtFixedRate(new RunnableImpl(){

			@Override
			public void runImpl() throws Exception
			{
				if(!player.isOnline())
					return;

				player.store(true);
			}

		}, delay, delay);
	}
}
